package com.cn.mobileproject.db.dao.impl;

import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.cn.mobileproject.bean.OrgRelation;
import com.cn.mobileproject.db.Query;
import com.cn.mobileproject.db.RowMapper;
import com.cn.mobileproject.db.SqliteTemplate;
import com.cn.mobileproject.db.UDatabase;
import com.cn.mobileproject.db.dao.OrgRelationDao;
import com.cn.mobileproject.db.table.OrgRelationTable;

public class OrgRelationDaoImpl implements OrgRelationDao{

	private SqliteTemplate sqliteTemplate;

	public OrgRelationDaoImpl() {
		sqliteTemplate = new SqliteTemplate();
	}


	@Override
	public void delete() {
		Query query = new Query();
		query.from(OrgRelationTable.TABLE_NAME);
		sqliteTemplate.delete(query);
	}

	@Override
	public void inserts(List<OrgRelation> list) {
		
		if(list==null||list.size()==0) return ;
		try{
			SQLiteDatabase db = UDatabase.getDb(true);
			db.beginTransaction();
			for(OrgRelation orgRelation: list){
				db.insert(OrgRelationTable.TABLE_NAME, null, orgToValues(orgRelation));
			}
			db.setTransactionSuccessful();
			db.endTransaction();
		}catch(Exception e){
		}
	}
	
	private ContentValues orgToValues(OrgRelation orgRelation) {
		ContentValues v = new ContentValues();
		v.put(OrgRelationTable.FIELD_USERID, orgRelation.userid);
		v.put(OrgRelationTable.FIELD_ORGID, orgRelation.orgid);
		return v;
	}

	private static final class OrgRelationMapper implements
			RowMapper<OrgRelation> {
		public OrgRelation mapRow(Cursor cursor, int rowNum) {
			OrgRelation orgrelation = new OrgRelation();
			if (cursor != null && cursor.getCount() > 0) {
				orgrelation.userid=cursor.getString(cursor.getColumnIndex(OrgRelationTable.FIELD_USERID));
				orgrelation.orgid=cursor.getString(cursor.getColumnIndex(OrgRelationTable.FIELD_ORGID));
			}
			return orgrelation;
		}
	}

	@Override
	public OrgRelation searchOrgRelation(String uid) {
		Query query = new Query();
		query.from(OrgRelationTable.TABLE_NAME, null).where(OrgRelationTable.FIELD_USERID + " = ?",uid);
		OrgRelation or = sqliteTemplate.queryForObject(query,new OrgRelationMapper());
		return or;
	}


	@Override
	public List<OrgRelation> searchUserByOrgId(String orgId) {
		Query query = new Query();
		query.from(OrgRelationTable.TABLE_NAME, null).where(OrgRelationTable.FIELD_ORGID + " = ?",orgId);
		return sqliteTemplate.queryForList(query,new OrgRelationMapper());
	}
}
